package com.cherrish.demo.thread;

/**
 * @author cherrish
 * @time 2019-03-20 13:38
 * @name JStackDemo
 * @desc:
 */
public class JStackDemo {
    public static void main(String[] args) {
        Thread t1 = new Thread(new DeadLockTest(true));
        Thread t2 = new Thread(new DeadLockTest(false));
        t1.setName("thread-dufy-1");
        t2.setName("thread-dufy-2");

        t1.start();
        t2.start();
    }
}

class DeadLockTest implements Runnable{

    //控制线程
    public boolean flag;

    public DeadLockTest(boolean flag) {
        this.flag = flag;
    }

    @Override
    public void run() {
        /**
         * 如果falg的值为true则调用t1线程
         */
        if(flag){
            while (true){
                synchronized (Demo.o1) {
                    System.out.println("o1 " + Thread.currentThread().getName());
                    synchronized (Demo.o2) {
                        System.out.println("o2 " + Thread.currentThread().getName());
                    }
                }
            }
        }else {
            /**
             * 如果falg的值为false则调用t2线程
             */
            while (true) {
                synchronized (Demo.o2) {
                    System.out.println("o2 " + Thread.currentThread().getName());
                    synchronized (Demo.o1) {
                        System.out.println("o1 " + Thread.currentThread().getName());
                    }
                }
            }
        }
    }
}

class Demo {
    static Object o1 = new Object();
    static Object o2 = new Object();
}